from django.db.models import Q
from django.shortcuts import render
from django.utils.datetime_safe import datetime
from rest_framework.response import Response
from rest_framework import status, viewsets
from .models import Follow
from .serializer import FollowSerializer, FollowDetailSerializer


# Create your views here.

class FollowViewSet(viewsets.ModelViewSet):
    serializer_class = FollowSerializer

    def get_queryset(self):
        queryset = Follow.objects.all()
        params = self.request.query_params
        if params:
            filters = {}
            for key, value in params.items():
                filters[key] = value
            queryset = queryset.filter(**filters)
        return queryset

    def get_follow_count(self, request, *args, **kwargs):
        fan = kwargs.get('fan')  # 从URL参数中获取视频的ID
        mup = kwargs.get('mup')  # 从URL参数中获取user的ID
        filters = Q(mup_id=mup) & Q(is_active=True)
        fan_count = Follow.objects.filter(filters).count()  # 查询关注数量
        filters = Q(fan_id=fan) & Q(is_active=True) & Q(mup_id=mup)
        is_fan = len(Follow.objects.filter(filters)) != 0
        return Response({'fan_count': fan_count, 'is_fan': is_fan}, status=status.HTTP_200_OK)

    def put_follow(self, request, *args, **kwargs):
        user = kwargs.get('user')
        Follow.objects.filter(fan=user).update(dynamic_last_time=datetime.now())
        return Response({'result': "OK"}, status=status.HTTP_200_OK)

    def put_follow_by_op(self, request, *args, **kwargs):
        pk = kwargs.get('pk')
        choice = kwargs.get('choice')
        Follow.objects.filter(foid=pk).update(is_active=choice != 0)
        return Response({'result': "OK"}, status=status.HTTP_200_OK)


class FollowDetailViewSet(viewsets.ModelViewSet):
    serializer_class = FollowDetailSerializer

    def get_queryset(self):
        queryset = Follow.objects.all()
        params = self.request.query_params
        if params:
            filters = {}
            for key, value in params.items():
                filters[key] = value
            queryset = queryset.filter(**filters)
        return queryset

    def get_my_follow(self, request, *args, **kwargs):
        user = kwargs.get('user')
        num = kwargs.get('num')
        from_index = kwargs.get('from')
        op = kwargs.get('op')
        result = []
        count = 0
        if op == 0:
            # 查询我的关注,我是粉丝
            follows = Follow.objects.filter(fan=user).filter(is_active=True).order_by('-time')
            count = len(follows)
            for i in range(from_index, min(num + from_index, count)):
                result.append(FollowDetailSerializer(follows[i]).data['mup'])
                result[-1].update(foid=follows[i].foid)
        else:
            # 查询我的粉丝，我是up
            follows = Follow.objects.filter(mup=user).filter(is_active=True).order_by('-time')
            count = len(follows)
            for i in range(from_index, min(num + from_index, count)):
                result.append(FollowDetailSerializer(follows[i]).data['fan'])
                result[-1].update(foid=follows[i].foid)
        return Response({'result': result, 'count': count}, status=status.HTTP_200_OK)
